package com.ogj.newstar.listener;

import com.ogj.newstar.NewstarNybikeApplication;
import com.ogj.newstar.util.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@WebListener  //添加Listener注解
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //应用初始化构造函数
        final Logger logger = LoggerFactory.getLogger(NewstarNybikeApplication.class);

        //1、先拿到ServletContext
        ServletContext servletContext = sce.getServletContext();
        //采用一个子线程 去访问数据
        Thread thread1 = new Thread(()->{
            //启动子线程的逻辑
            String infoUrl="https://gbfs.citibikenyc.com/gbfs/en/station_information.json";
            String statusUrl="https://gbfs.citibikenyc.com/gbfs/en/station_status.json";

            while (true){
                //请求信息数据状态数据
                String infoData = HttpUtils.get(infoUrl);
                String statusData = HttpUtils.get(statusUrl);
                //缓存到ServletContext
                servletContext.setAttribute("infoData",infoData);
                servletContext.setAttribute("statusData",statusData);
                System.err.println(new Date().toString()+",获取数据=> infoData:"+infoData.length()+", StatusData:" +statusData.length());
//                log.println(System.currentTimeMillis()+"获取数据=> infoData:"+infoData.length()+", StatusData:"+statusData.length());
                logger.debug("获取数据=> infoData:"+infoData.length()+", StatusData:" +statusData.length());
                try {
                    //休息30s 再获取数据
                    TimeUnit.SECONDS.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //应用即将销毁时执行的函数
    }
}
